package com.gillion.grape.fros.ui.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

/**<pre>文件工具类</pre>
 * @Author   KOO
 * @Version  1.0
 * @Date     2009-12-14
 * @example  使用示例：略。
 */
public class FU {
	
	private final static int DEFAULT_BUFFER_SIZE = 512;
	
	/**
	 * 保存字符串results至指定路徑（filePath）的文件，如果文件路徑不存在則自動創建
	 * @param result
	 * @param filePath
	 */
	public static void saveStringToFile(String result, String filePath) {
		FU.saveStringToFile(result, new File(filePath));
	}
	
	/**
	 * 打开指定文件，并将文件内容读入字符串中
	 * @param result
	 * @param filePath
	 */
	// 2010/10/19 Alex
	public static String readStringFromFile(String filePath) {
		File file = new File(filePath);
		if(!file.exists()){
			return null;
		}
		InputStreamReader reader = null; 
		StringWriter writer = new StringWriter(); 
		try { 
			reader = new InputStreamReader(new FileInputStream(file), "UTF-8"); 
			char[] buffer = new char[DEFAULT_BUFFER_SIZE]; 
			int n = 0; 
			while (-1 != (n = reader.read(buffer))) { 
				writer.write(buffer, 0, n); 
			} 
		} catch (Exception e) { 
			e.printStackTrace(); 
			return null; 
		} finally { 
			if (reader != null) 
				try { 
					reader.close(); 
				} catch (IOException e) { 
					e.printStackTrace(); 
				} 
		} 
		//返回转换结果 
		if (writer != null) 
			return writer.toString(); 
		else 
			return null; 
	}

	/**
	 * 保存字符串results至指定文件中，如果文件路徑不存在則自動創建
	 * @param result
	 * @param filePath
	 */
	public static void saveStringToFile(String result, File file) {
		if(result == null){
			result = "";
		}
		FU.makeFilesDirExist(file.getPath());
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(result.getBytes("UTF-8"));
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void makeFilesDirExist(String filePath){
		String dirPath = filePath.substring(0, filePath.lastIndexOf(File.separator));
		File dir = new File(dirPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}	
	}
	
	/**
	 * 删除路径为filePath对应的文件
	 * @param filePath
	 */
	public static void deleteFile(String filePath){
		File file = new File(filePath);
		if(file.exists()){
			try {
				FileUtils.forceDelete(file);
			} catch (IOException e) {
				// TODO
				e.printStackTrace();
			}
		}
	}
	
	public static void copyFile(File fromFile, File toFile) {
		try {
			FileInputStream fis = new FileInputStream(fromFile);
			FileOutputStream fos = new FileOutputStream(toFile);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
			fis.close();
			fos.close();
		} catch (Exception ex) {
			throw new RuntimeException("拷贝文件失败", ex);
		}
	}
	
	public static void copyFile(String fromFilePath, String toFilePath){
		File fromFile = new File(fromFilePath);
		File toFile = new File(toFilePath);
		FU.copyFile(fromFile, toFile);
	}
	
	public static void copyDir(String fromDirPath, String toDirPath){
		File fromDir = new File(fromDirPath);
		File toDir = new File(toDirPath);
		try {
			FileUtil.copyDir(fromDir, toDir);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void copyDir(String fromDirPath, String toDirPath, String excludedDirName){
		File fromDir = new File(fromDirPath);
		File toDir = new File(toDirPath);
		try {
			FileUtil.copyDir(fromDir, toDir, excludedDirName);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean exist(String filePath){
		File file = new File(filePath);
		return file.exists();
	}
	
	public static boolean notExist(String filePath){
		File file = new File(filePath);
		return !file.exists();
	}
	
	/**
	 * 当filePath对应的文件不存在时，创建该文件
	 * @param filePath
	 */
	public static void createFileWhenNotExist(String filePath){
		File file = new File(filePath);
		if(!file.exists()){
			try {
				makeFilesDirExist(filePath);
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 批量修改文件夹下面的扩展名
	 * @param dirPath
	 * @param originalExtension
	 * @param newExtension
	 */
	public static void renameExtension(String dirPath, String originalExtension, String newExtension){
		File file = new File(dirPath);
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for(File fileIn : files){
				if(fileIn.isDirectory()){
					renameExtension(fileIn.getPath(), originalExtension, newExtension);
				} else {
					String originalFilePath = fileIn.getPath();
					if(originalFilePath.endsWith(originalExtension)){
						String newFilePath = originalFilePath.substring(0, originalFilePath.lastIndexOf(originalExtension)) + newExtension;
						if(exist(newFilePath)){
							deleteFile(newFilePath);
						}
						File fileNew = new File(newFilePath);
						fileIn.renameTo(fileNew);
					}
				}
			}
		}
	}
	
	/**
	 * 删除目录
	 * @param filePath
	 * @throws IOException
	 */
	public static void delFileDir(String filePath) throws IOException{
		File f = new File(filePath);//定义文件路径       
		if(f.exists() && f.isDirectory()){//判断是文件还是目录
		   if(f.listFiles().length==0){//若目录下没有文件则直接删除
		      f.delete();
		   }else{//若有则把文件放进数组，并判断是否有下级目录
		       File delFile[]=f.listFiles();
		       int i = f.listFiles().length;
		       for(int j=0;j<i;j++){
		           if(delFile[j].isDirectory()){
		        	   delFileDir(delFile[j].getAbsolutePath());//递归调用delFileDir方法并取得子目录路径
		           }
		           delFile[j].delete();//删除文件
		       }
		   }
		}
	}    
	
	/**
	 * 获取目录下所有文件
	 * 
	 * @param path
	 * @return
	 */
	public static List<String> getListFiles(String path) {
		List<String> fileList = new ArrayList<String>();
		File file = new File(path);
		if(file.exists()){
			File[] t = file.listFiles();
			for (int i = 0; i < t.length; i++) {
				if(t[i].isFile()){
					fileList.add(t[i].getAbsolutePath());
				}
			}
		}
		return fileList;
	}
}
